﻿using System;
using System.Linq;
using System.Web;
using System.Web.Security;

namespace PegasCompany.HttpModules
{
    public class SecurityHttpModule : IHttpModule
    {
        #region IHttpModule Members

        public void Dispose()
        {
            //clean-up code here.
        }

        public void Init(HttpApplication context)
        {
            // Below is an example of how you can handle LogRequest event and provide 
            // custom logging implementation for it
            context.LogRequest += new EventHandler(OnLogRequest);
            context.AuthenticateRequest += new EventHandler(this.AuthenticateRequest);
        }

        /// <summary>Occurs when a security module
        /// has established the identity of the user.</summary>
        private void AuthenticateRequest(Object sender, EventArgs e)
        {
            HttpApplication application = (HttpApplication)sender;
            HttpRequest request = application.Context.Request;
            HttpResponse response = application.Context.Response;
            bool allow = false; // Default is not not allow

            // Exit if we're on login.aspx,
            // not authenticated, or no siteMapNode exists.
            if (request.Url.AbsolutePath.ToLower() == FormsAuthentication.LoginUrl.ToLower()) 
                return;
            
            if (application.Context.User == null)
                response.Redirect(FormsAuthentication.LoginUrl);
            
            if (SiteMap.CurrentNode == null) 
                return;

            // Check if user is in roles
            if (SiteMap.CurrentNode.Roles.Count == 0)
            {
                allow = true; // No Roles found, so we allow.
            }
            else
            {
                // Loop through each role and check to see if user is in it.
                //foreach (string role in SiteMap.CurrentNode.Roles)
                //{
                //    if (Roles.IsUserInRole(role))
                //    {
                //        allow = true; break;
                //    }
                //}
                if (SiteMap.CurrentNode.Roles.Cast<string>().Any(role => Roles.IsUserInRole(role)))
                {
                    allow = true;
                }
            }

            // Do we deny?
            if (allow == false)
                response.Redirect(FormsAuthentication.LoginUrl);
        }

        #endregion

        public void OnLogRequest(Object source, EventArgs e)
        {
            //custom logging logic can go here
        }
    }
}
